package com.yunji.news.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunji.news.common.Result;
import com.yunji.news.dto.AnnualEnrollmentInfoWithSchoolDTO;
import com.yunji.news.entity.AnnualEnrollmentInfo;
import com.yunji.news.entity.School;
import com.yunji.news.service.AnnualEnrollmentInfoService;
import com.yunji.news.service.SchoolService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 年度招生信息控制器（公开接口）
 *
 * @author yunji
 * @since 2025-11-27
 */
@RestController
@RequestMapping("/annual-enrollment")
@RequiredArgsConstructor
public class AnnualEnrollmentController {

    private final AnnualEnrollmentInfoService annualEnrollmentInfoService;
    private final SchoolService schoolService;

    /**
     * 分页查询年度招生信息（包含学校信息）
     *
     * @param current 当前页
     * @param size 每页大小
     * @param year 年份
     * @param schoolName 学校名称
     * @return 分页数据
     */
    @GetMapping
    public Result<IPage<AnnualEnrollmentInfoWithSchoolDTO>> getPage(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "20") Long size,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) String schoolName) {

        Page<AnnualEnrollmentInfo> page = new Page<>(current, size);
        
        // 构建查询条件
        LambdaQueryWrapper<AnnualEnrollmentInfo> wrapper = new LambdaQueryWrapper<AnnualEnrollmentInfo>()
                .eq(year != null, AnnualEnrollmentInfo::getYear, year)
                .eq(AnnualEnrollmentInfo::getStatus, 1) // 只查询启用状态
                .orderByAsc(AnnualEnrollmentInfo::getSortOrder)
                .orderByDesc(AnnualEnrollmentInfo::getCreatedAt);

        IPage<AnnualEnrollmentInfo> enrollmentPage = annualEnrollmentInfoService.page(page, wrapper);
        
        // 获取所有学校信息
        List<School> allSchools = schoolService.list(new LambdaQueryWrapper<School>()
                .eq(School::getStatus, 1));
        Map<Long, School> schoolMap = allSchools.stream()
                .collect(Collectors.toMap(School::getId, school -> school));

        // 转换为DTO并填充学校信息
        List<AnnualEnrollmentInfoWithSchoolDTO> dtoList = enrollmentPage.getRecords().stream()
                .map(enrollment -> {
                    AnnualEnrollmentInfoWithSchoolDTO dto = new AnnualEnrollmentInfoWithSchoolDTO();
                    BeanUtils.copyProperties(enrollment, dto);
                    
                    // 填充学校信息
                    School school = schoolMap.get(enrollment.getSchoolId());
                    if (school != null) {
                        dto.setSchoolName(school.getName());
                        dto.setSchoolShortName(school.getShortName());
                        
                        // 如果有学校名称筛选，进行过滤
                        if (StringUtils.hasText(schoolName) && 
                            !school.getName().contains(schoolName)) {
                            return null; // 过滤掉不匹配的记录
                        }
                    }
                    return dto;
                })
                .filter(dto -> dto != null)
                .collect(Collectors.toList());

        // 创建结果页面
        Page<AnnualEnrollmentInfoWithSchoolDTO> resultPage = new Page<>(current, size);
        resultPage.setRecords(dtoList);
        resultPage.setTotal(enrollmentPage.getTotal());
        resultPage.setSize(enrollmentPage.getSize());
        resultPage.setCurrent(enrollmentPage.getCurrent());

        return Result.success(resultPage);
    }
    
    /**
     * 根据功能类型获取年度招生信息
     * 
     * @param year 年份
     * @param type 功能类型：registration|qualified|payment|exam|admission
     * @return 招生信息列表
     */
    @GetMapping("/by-type")
    public Result<List<AnnualEnrollmentInfoWithSchoolDTO>> getByType(
            @RequestParam(defaultValue = "2025") Integer year,
            @RequestParam String type) {

        LambdaQueryWrapper<AnnualEnrollmentInfo> wrapper = new LambdaQueryWrapper<AnnualEnrollmentInfo>()
                .eq(AnnualEnrollmentInfo::getYear, year)
                .eq(AnnualEnrollmentInfo::getStatus, 1)
                .orderByAsc(AnnualEnrollmentInfo::getSortOrder);

        List<AnnualEnrollmentInfo> enrollmentList = annualEnrollmentInfoService.list(wrapper);
        
        // 获取学校信息
        List<School> allSchools = schoolService.list(new LambdaQueryWrapper<School>()
                .eq(School::getStatus, 1));
        Map<Long, School> schoolMap = allSchools.stream()
                .collect(Collectors.toMap(School::getId, school -> school));

        // 转换为DTO并填充学校信息
        List<AnnualEnrollmentInfoWithSchoolDTO> dtoList = enrollmentList.stream()
                .map(enrollment -> {
                    AnnualEnrollmentInfoWithSchoolDTO dto = new AnnualEnrollmentInfoWithSchoolDTO();
                    BeanUtils.copyProperties(enrollment, dto);
                    
                    // 填充学校信息
                    School school = schoolMap.get(enrollment.getSchoolId());
                    if (school != null) {
                        dto.setSchoolName(school.getName());
                        dto.setSchoolShortName(school.getShortName());
                    }
                    return dto;
                })
                .collect(Collectors.toList());

        return Result.success(dtoList);
    }
}